package wavenotes;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.google.appengine.api.datastore.KeyFactory;
import com.google.inject.Singleton;

import wavenotes.model.PMF;
import wavenotes.model.image.DatastoreImage;
import wavenotes.model.image.ImageFactory;

@Singleton
public class ImageServlet extends HttpServlet {
	private static final long serialVersionUID = 2060849085319434762L;
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		if (ServletFileUpload.isMultipartContent(req)) {
			try {
				handleImageUpload(req, resp);
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
		}
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		getImage(req, resp);
	}
	
	private void getImage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		DatastoreImage image = pm.getObjectById(DatastoreImage.class, req.getParameter("imageKey"));
		
		String size = "original";
		if (req.getParameter("size") != null) {
			size = req.getParameter("size");
		}
		
		if (image == null) {
			throw new ServletException("File not found.");
		}
		
		byte[] imageBytes = null;
		if (size.equals("small")) {
			imageBytes = image.getSmallImage().getBytes();
		} else if (size.equals("original")) {
			imageBytes = image.getOriginalImage().getBytes();
		}
		
		resp.setContentType("image/png");
		resp.setContentLength(imageBytes.length);
		
		resp.getOutputStream().write(imageBytes);
	}
	
	/**
	 * Puts uploaded images (must be pngs) in the datastore.  Returns
	 * a list of the keys (separated by line breaks).
	 */
	private void handleImageUpload(HttpServletRequest req, HttpServletResponse resp) 
		throws ServletException, FileUploadException, IOException {
		
		ServletFileUpload upload = new ServletFileUpload();
		FileItemIterator iterator = upload.getItemIterator(req);
		List<DatastoreImage> datastoreImages = new ArrayList<DatastoreImage>();
		
		while (iterator.hasNext()) {
			FileItemStream item = iterator.next();
			InputStream stream = item.openStream();
			
			if (!item.isFormField()) {
				if (!item.getName().equals("")) {
					datastoreImages.add(ImageFactory.createImage(Util.readStream(stream)));
				}
			}
		}
				
		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.makePersistentAll(datastoreImages);
		
		for (DatastoreImage image : datastoreImages) {
			resp.getWriter().println(KeyFactory.keyToString(image.getKey()));
		}
		
		pm.close();
	}
}
